//
//  XDRelativeMgrViewController.m
//  XDEducation
//
//  Created by apple on 2017/5/4.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDRelativeMgrViewController.h"
#import "XDTeacherMgrViewController.h"
#import "XDChildMgrViewController.h"
#import "HNRelativeModel.h"

@interface XDRelativeMgrViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, weak)  UIView *titleView;
@property (nonatomic, strong) NSMutableArray *buttons;
@property (nonatomic, weak) UIButton *selectButton;
@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, weak) UIView *underLineView;

@property (nonatomic, strong) NSMutableArray *DataArr;
@end


static NSString * ID = @"RelativeMgr";

@implementation XDRelativeMgrViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    

    
    [self RefreshData];
}



#pragma mark - 网络请求
- (void)RefreshData
{
    [MBProgressHUD showHUD];
    NSString *UrlStr = [NSString stringWithFormat:@"qun.do?action=getqun&uid=%@",[AccountTool shareAccountTool].currentAccount.uid];
    [XDHttpTool get:BaseURL(UrlStr) authCode:[AccountTool shareAccountTool].currentAccount.authCode params:nil success:^(id responseObj) {
        
        if (responseObj)
        {
            for (NSDictionary *Dict in responseObj[@"qusers"])
            {
                HNRelativeModel *Model = [[HNRelativeModel alloc] init_HNWithObject:Dict];
                Model.qid = responseObj[@"qid"];
                [self.DataArr addObject:Model];
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
               
                //初始化导航栏
                
                // 添加底部内容view
                [self setupBottomView];
                
                //添加子控制器
                [self setUpChildViewController];
                
                //设置标题View
                [self setUpTitleView];
                
                // 不需要自动添加额外滚动区域
                self.automaticallyAdjustsScrollViewInsets = NO;
                
            });
            
            

        }
        else
        {
            [MBProgressHUD showError:responseObj[@"data"][@"t"]];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:XDNetWorkError];
    }];
}









#pragma mark - 懒加载按钮数组
- (NSMutableArray *)buttons
{
    if (_buttons == nil) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}


- (NSMutableArray *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}


- (void)setupBottomView
{
    // 布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = [UIScreen mainScreen].bounds.size;
    
    // 设置滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    // UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH) collectionViewLayout:layout];
    
    //collectionView.backgroundColor = UIColor(215, 215, 215);
    collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:collectionView];
    // 不显示水平指示器
    collectionView.showsHorizontalScrollIndicator = NO;
    // 开启分页
    collectionView.pagingEnabled = YES;
    _collectionView = collectionView;
    // 设置collectionView数据源,展示cell,需要把子控制器view添加cell
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    // 注册cell
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}


#pragma mark -添加所有子控制器
- (void)setUpChildViewController {
    
    NSMutableArray *ChildArr = [NSMutableArray array];
    NSMutableArray *RelativeArr = [NSMutableArray array];
    NSMutableArray *TeacherArr = [NSMutableArray array];
    
    for (HNRelativeModel *Model in self.DataArr)
    {
        if ([Model.gradeid isEqualToNumber:@2])
        {
            [TeacherArr addObject:Model];
        }
        else if ([Model.gradeid isEqualToNumber:@3])
        {
            [RelativeArr addObject:Model];
        }
        else if ([Model.gradeid isEqualToNumber:@4])
        {
            [ChildArr addObject:Model];
        }
    }
    
    //孩子
    XDChildMgrViewController *childMgrVC = [[XDChildMgrViewController alloc] init];
    childMgrVC.title = @"孩子";
    childMgrVC.DataArr = [ChildArr copy];
    [self addChildViewController:childMgrVC];
    
    //亲人
    XDTeacherMgrViewController *relativeVC = [[XDTeacherMgrViewController alloc] init];
    relativeVC.title =  @"亲人";
    relativeVC.DataArr = [RelativeArr copy];
    [self addChildViewController:relativeVC];
    
    
    //老师
    XDTeacherMgrViewController *teacherVC = [[XDTeacherMgrViewController alloc]init];
    teacherVC.title = @"老师";
    teacherVC.DataArr = [TeacherArr copy];
    [self addChildViewController:teacherVC];
    
    
}


#pragma mark -添加标题View
- (void)setUpTitleView {
    
    CGFloat titleViewX = 40;
    CGFloat titleViewY = 0;
    CGFloat titleViewW = ScreenW - 80;
    CGFloat titleViewH = 44;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(titleViewX, titleViewY, titleViewW, titleViewH)];
    self.titleView = titleView;
    titleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:titleView];
    
    NSInteger count = self.childViewControllers.count;
    CGFloat titleBtnW = (ScreenW - 80) / count;
    CGFloat titleBtnH = titleView.height;
    CGFloat titleBtnX = 0;
    CGFloat titleBtnY = 0;
    for (int i = 0; i < count; i++) {
        
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        titleBtn.tag = i;
        UIViewController *vc = self.childViewControllers[i];
        [titleBtn setTitle:vc.title forState:UIControlStateNormal];
        [titleBtn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        [titleBtn setTitleColor:ThemeColor forState:UIControlStateSelected];
        titleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        titleBtnX = titleBtnW * i;
        titleBtn.frame = CGRectMake(titleBtnX, titleBtnY, titleBtnW, titleBtnH);
        [titleView addSubview:titleBtn];
        [self.buttons addObject:titleBtn];
        // 监听按钮
        [titleBtn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //在这设置button初始的选择状态
        if (i == _selectedButtonTag) {
            
            // 添加下划线
            UIView *underLineView = [[UIView alloc] init];
            underLineView.backgroundColor = ThemeColor;
            [titleView addSubview:underLineView];
            _underLineView = underLineView;
            
            // 中心点x
            underLineView.height = 2;
            underLineView.y = titleView.height - underLineView.height;
            // 1.根据控件内容计算尺寸,然后给控件设置尺寸
            [titleBtn.titleLabel sizeToFit];
            underLineView.width = titleBtn.titleLabel.width + 50;
            // 一定要先设置尺寸 在设置中心点
            underLineView.centerX = titleBtn.centerX;
            
            [self titleClick:titleBtn];
        }
        
        
    }
}


-(void)setSelectedButtonTag:(NSInteger)selectedButtonTag{
    
    _selectedButtonTag = selectedButtonTag;
    //NSLog(@"%ld",(long)_selectedButtonTag);
}

#pragma mark - 选中按钮
- (void)selButton:(UIButton *)button
{
    //重复点击同一个按钮 刷新页面
    //if (_selectButton == button) {
    //    NSString *selectRefreshController = [NSString stringWithFormat:@"refreshView%ld",(long)button.tag];
    //    NSNotification * refresh = [NSNotification notificationWithName:selectRefreshController object:nil userInfo:@{@"tag":@"123"}];
    //    [[NSNotificationCenter defaultCenter] postNotification:refresh];
    //}
    _selectButton.selected = NO;
    button.selected = YES;
    _selectButton = button;
    
    // 修改下划线位置
    [UIView animateWithDuration:0.25 animations:^{
        _underLineView.centerX = button.centerX;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }];
    
}

#pragma mark - 点击标题
- (void)titleClick:(UIButton *)button
{
    NSInteger i = button.tag;
    // 1.选中按钮
    [self selButton:button];
    
    // 2.设置collectionView偏离量
    CGFloat offsetX = i * ScreenW;
    _collectionView.contentOffset = CGPointMake(offsetX, 0);
}


#pragma mark - UICollectionViewDelegate
// 滚动完成的时候就会调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 获取页码
    NSInteger page = scrollView.contentOffset.x / ScreenW;
    
    // 获取标题按钮
    UIButton *titleButton = self.buttons[page];
    
    // 选中标题
    [self selButton:titleButton];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.childViewControllers.count;
}

// 只要有新的cell出现就会调用
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    // 移除其它子控制器view
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    // 添加对应的子控制器view 到 对应cell
    UIViewController *vc = self.childViewControllers[indexPath.row];
    // 添加到contentView
    [cell.contentView addSubview:vc.view];
    
    //    cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
    //
    return cell;
}



@end
